#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <iostream>
#include "tiles.h"
#include "milkrace.h"

SDL_Event event;
SDL_Surface *display;
SDL_Surface *font;
R8B_Tiled_Screen *scr;

int main(int argc, char **argv) {
  bool running = true;
  SDL_Rect rect = { 30, 20, 640, 480 };

  if(SDL_Init(SDL_INIT_EVERYTHING) != 0) {
    std::cerr << SDL_GetError() << std::endl;
    return 5;
  }
  atexit(SDL_Quit);
  display = SDL_SetVideoMode(700, 520, 32, SDL_HWSURFACE);
  if(display == NULL) {
    std::cerr << "Video mode failed!\n";
    return 5;
  }
  SDL_EnableUNICODE(1);
  SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  font = get_milkrace_surfaceX2();
  if((scr = r8b_createTiledScreen_using_surface(40, 30, ' ', font, 16, 16)) == NULL) {
    std::cerr << "Aborting! Error while creating tiled screen.\n";
  }
  SDL_FillRect(display, NULL, SDL_MapRGB(display->format, 0, 0xff, 0xff));
  SDL_FillRect(display, &rect, SDL_MapRGB(display->format, 0, 0xCC, 0xCC));  
  r8b_printStringScreenLn(scr, r8b_c64CharConversionFun, "hello and welcome!");
  r8b_printStringScreenLn(scr, r8b_c64CharConversionFun, "");
  r8b_printStringScreenLn(scr, r8b_c64CharConversionFun, "this is a simple example how to use the text screen. we are using a c64 style font...");
  while(running && SDL_WaitEvent(&event)) {
    SDL_FillRect(display, &rect, SDL_MapRGB(display->format, 0, 0xCC, 0xCC));  
    r8b_blitScreenXY(scr, display, 30, 20);
    SDL_Flip(display);
    switch(event.type) {
    case SDL_KEYDOWN:
      if(event.key.keysym.sym == SDLK_ESCAPE)
	running = false;
      else if((event.key.keysym.unicode != 0) && ((event.key.keysym.unicode & 0xFF80) == 0)) {
	char ch = event.key.keysym.unicode & 0x7F;
	//std::cout << (int)ch << '\n';
	if(ch == 13)
	  r8b_printStringScreenLn(scr, r8b_c64CharConversionFun, "");
	else
	  r8b_putCharScreen(scr, r8b_c64CharConversionFun(ch));
      }
      break;
    default:
      break;
    }
  }
  for(int i = 1; i < 480; ++i) {
    SDL_Rect r = { 0, i, 640, 480 };
    SDL_Rect d = { 30, 20, 0, 0 };
    SDL_FillRect(display, &rect, SDL_MapRGB(display->format, 0, 0xCC*(1.0-i/480.0), 0xCC*(1-i/480.0)));  
    r8b_blitScreenPart(scr, &r, display, &d);
    SDL_Flip(display);
    SDL_Delay(10);
  }
  r8b_freeTiledScreen(scr);
  SDL_FreeSurface(font);
  SDL_FreeSurface(display);
  return 0;
};
